package com.zzyl.nursing.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationMemberDto;
import com.zzyl.nursing.mapper.ReservationMemberMapper;
import com.zzyl.nursing.service.IReservationMemberService;
import com.zzyl.nursing.vo.ReservationMemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ReservationMemberServiceImpl extends ServiceImpl<ReservationMemberMapper, Reservation> implements IReservationMemberService {
    @Autowired
    private ReservationMemberMapper reservationMemberMapper;
    /**
     * 取消预约
     * */
    @Override
    public String cancelReservation(Long id) {
        reservationMemberMapper.cancelReservation(id);
        return "取消成功";
    }
    /**
     * 查询预约登记列表
     *
     * @param reservation 预约登记
     * @return 预约登记
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        Long fid = UserThreadLocal.getUserId();
        return reservationMemberMapper.selectReservationList(reservation,fid);
    }
    /**
     * 查询取消预约数量
     * */
    @Override
    public Long selectReservationList() {
        return reservationMemberMapper.findReservationList(UserThreadLocal.getUserId());
    }

    @Override
    public List<ReservationMemberVo> countByTime(long time) {

        List<ReservationMemberVo> reservationMemberVoList = new ArrayList<ReservationMemberVo>();
        List<LocalDateTime> timeSlots = generateTimeSlots(time);
        reservationMemberVoList = reservationMemberMapper.countByTime(timeSlots);
        return reservationMemberVoList;
    }

    @Transactional
    @Override
    public String addReservationMember(ReservationMemberDto reservationMemberDto) {
        //预约6次无法预约
        /*if(reservationMemberMapper.countByTime(reservationMemberDto.getTime()) > 5) {
            throw new BaseException("预约6次无法预约");
        }*/
        //当日取消三次无法预约
        /*if(reservationMemberMapper.findReservationList(UserThreadLocal.getUserId()) > 3) {
            throw new BaseException("当日取消次数已满");
        }*/
        //内容是否为空
        if(StringUtils.isEmpty(reservationMemberDto.getMobile())) {
            throw new BaseException("手机号不能为空");
        }
        if(StringUtils.isEmpty(reservationMemberDto.getName())) {
            throw new BaseException("姓名不能为空");
        }
        if(reservationMemberDto.getTime() == null) {
            throw new BaseException("预约时间不能为空");
        }
        if(StringUtils.isEmpty(reservationMemberDto.getVisitor())) {
            throw new BaseException("探访人不能为空");
        }
        if(reservationMemberDto.getType() == null) {
            throw new BaseException("预约类型不能为空");
        }
        //手机号格式是否正确
        if(!isValidMobile(reservationMemberDto.getMobile())) {
            throw new BaseException("手机号格式错误");
        }
        //手机号是否预约过此时间
        if(reservationMemberMapper.isAppointment(reservationMemberDto.getMobile(),reservationMemberDto.getTime()) > 0) {
            throw new BaseException("手机号已预约过此时间");
        }
        //家人是否已退住
        if(reservationMemberMapper.isStatus(reservationMemberDto.getVisitor()) > 0){
            throw new BaseException("未查询到老人");
        }

        reservationMemberDto.setCreateBy(UserThreadLocal.getUserId());
        reservationMemberDto.setUpdateBy(UserThreadLocal.getUserId());
        reservationMemberDto.setCreateTime(LocalDateTime.now());
        reservationMemberDto.setUpdateTime(LocalDateTime.now());
        reservationMemberDto.setStatus(0);
        reservationMemberMapper.addReservationMember(reservationMemberDto);
        return "预约成功";

    }

    /**
     * 验证手机号格式是否正确
     * @param mobile 手机号
     * @return 是否有效
     */
    private boolean isValidMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        // 手机号正则表达式：11位数字，以1开头，第二位为3-9
        String mobilePattern = "^1[3-9]\\d{9}$";
        return mobile.matches(mobilePattern);
    }

    /**
     * 时间段生成
     * */
    public static List<LocalDateTime> generateTimeSlots(long timestamp) {
        List<LocalDateTime> timeSlots = new ArrayList<>();

        // 将时间戳转换为LocalDate（使用系统默认时区）
        Date date = new Date(timestamp);
        LocalDate localDate = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 设置开始和结束时间
        LocalTime startTime = LocalTime.of(8, 0);   // 上午08:00开始
        LocalTime endTime = LocalTime.of(18, 0);    // 下午18:00结束

        // 生成时间段
        LocalTime currentTime = startTime;
        while (!currentTime.isAfter(endTime)) {
            // 将日期和时间组合成LocalDateTime
            LocalDateTime dateTime = LocalDateTime.of(localDate, currentTime);
            timeSlots.add(dateTime);
            currentTime = currentTime.plusMinutes(30);  // 每半小时增加
        }

        return timeSlots;
    }

}
